﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Authentication;
using System.Threading;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.Utils;
using DevExpress.XtraBars.Docking2010.Views;
using DevExpress.XtraBars.Docking2010.Views.WindowsUI;
using DevExpress.XtraEditors;
using EduFormManager.Forms;
using EduFormManager.Forms.Reports;
using EduFormManager.Forms.UserControls;
using EduFormManager.Forms.UserControls.QueryControl;
using EduFormManager.Models;
using EduFormManager.Models.Log;
using EduFormManager.Models.Repo;
using EduFormManager.Properties;
using EduFormManager.Utilities;
using EduFormManager.Utils;

namespace EduFormManager
{
    public partial class mainForm : XtraForm
    {
        private static NLog.Logger logger = NLog.LogManager.GetLogger("app");

        AuthenticationForm authForm;
        MarqueeProgressDialog progressDialog;
        Authentication auth;

        XtraDictionaryEduPassportControl passportControl;
        XtraMessageControl messageControl;
        XtraSpreadsheet sheetControl;

        public mainForm()
        {
            InitializeComponent();
            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            this.Text = "CMO Statistics " + version;

            if (!DesignMode)
            {
                progressDialog = new MarqueeProgressDialog();
                authForm = new AuthenticationForm(Settings.Default.LastLogin);

                auth = new Authentication();

                passportControl = new XtraDictionaryEduPassportControl(this.windowsUIViewMain);
                messageControl = new XtraMessageControl(this.windowsUIViewMain);
            }
            UserLookAndFeel.Default.SetSkinStyle("Office 2013");
            this.SizeChanged += mainForm_SizeChanged;
            this.mainForm_SizeChanged(this, null);

            tileContainerMain.Items.Remove(tileDictionaries);
            tileContainerMain.Items.Remove(tileDocumentQueries);
            tileContainerMain.Items.Remove(tileMessageList);
            tileContainerMain.Items.Remove(tileMessage);
            tileContainerMain.Items.Remove(tileFormStatistics);
            tileContainerMain.Items.Remove(tileEduPasport);
            tileContainerMain.Items.Remove(tileSpreadsheet);
            tileContainerMain.Items.Remove(tileMunicipalityForms);
            tileContainerMain.Items.Remove(tileArchiveMunicipalityForms);
            tileContainerMain.Items.Remove(tileDictQuestionary);
            tileContainerMain.Items.Remove(tileCreateQuery);}

        async void SomeInitialization()
        {
            progressDialog.ShowTop(this);

            SynchronizationContext context = SynchronizationContext.Current;
            GuiHelper.GuiThreadContext = context;

            Dictionary<string, TileContainer> dictContainers = await GuiHelper.CreateTileContainersAsync(Authentication.CurrentCredentials, windowsUIViewMain);
            //await GuiHelper.CreateTileContainersAsync(Authentication.CurrentCredentials, windowsUIViewMain);
            //new Dictionary<string, TileContainer>(); 
            if (dictContainers.ContainsKey(TagHelper.FEDERAL_EDU_FORMS_TAG))
            {
                this.tileForms.ActivationTarget = dictContainers[TagHelper.FEDERAL_EDU_FORMS_TAG];
                this.tileForms.Tag = TagHelper.FEDERAL_EDU_FORMS_TAG;
                this.tileForms.ActivationTarget.Parent = this.tileContainerMain;
            }
            if (dictContainers.ContainsKey(TagHelper.ARCHIVE_FEDERAL_EDU_FORMS_TAG))
            {
                this.tileArchiveForms.ActivationTarget = dictContainers[TagHelper.ARCHIVE_FEDERAL_EDU_FORMS_TAG];
                this.tileArchiveForms.Tag = TagHelper.ARCHIVE_FEDERAL_EDU_FORMS_TAG;
                this.tileArchiveForms.ActivationTarget.Parent = this.tileContainerMain;
            }
            if (dictContainers.ContainsKey(TagHelper.ADDON_EDU_FORMS_TAG))
            {
                this.tileAdditionalForms.ActivationTarget = dictContainers[TagHelper.ADDON_EDU_FORMS_TAG];
                this.tileAdditionalForms.Tag = TagHelper.ADDON_EDU_FORMS_TAG;
                this.tileAdditionalForms.ActivationTarget.Parent = this.tileContainerMain;
            }
            if (dictContainers.ContainsKey(TagHelper.ARCHIVE_ADDON_EDU_FORMS_TAG))
            {
                this.tileArchiveAdditionalForms.ActivationTarget = dictContainers[TagHelper.ARCHIVE_ADDON_EDU_FORMS_TAG];
                this.tileArchiveAdditionalForms.Tag = TagHelper.ARCHIVE_ADDON_EDU_FORMS_TAG;
                this.tileArchiveAdditionalForms.ActivationTarget.Parent = this.tileContainerMain;
            }
            if (dictContainers.ContainsKey(TagHelper.FEDERAL_MUNIT_FORMS_TAG))
            {
                this.tileMunicipalityForms.ActivationTarget = dictContainers[TagHelper.FEDERAL_MUNIT_FORMS_TAG];
                this.tileMunicipalityForms.Tag = TagHelper.FEDERAL_MUNIT_FORMS_TAG;
                this.tileMunicipalityForms.ActivationTarget.Parent = this.tileContainerMain;
            }
            if (dictContainers.ContainsKey(TagHelper.ARCHIVE_FEDERAL_MUNIT_FORMS_TAG))
            {
                this.tileArchiveMunicipalityForms.ActivationTarget = dictContainers[TagHelper.ARCHIVE_FEDERAL_MUNIT_FORMS_TAG];
                this.tileArchiveMunicipalityForms.Tag = TagHelper.ARCHIVE_FEDERAL_MUNIT_FORMS_TAG;
                this.tileArchiveMunicipalityForms.ActivationTarget.Parent = this.tileContainerMain;
            }
            if (dictContainers.ContainsKey(TagHelper.QUESTIONARY_TAG))
            {
                this.tileDictQuestionary.ActivationTarget = dictContainers[TagHelper.QUESTIONARY_TAG];
                this.tileDictQuestionary.Tag = TagHelper.QUESTIONARY_TAG;
                this.tileDictQuestionary.ActivationTarget.Parent = this.tileContainerMain;
            }

            tileEduPasport.Elements[1].Text = Authentication.CurrentCredentials.Name;

            tileMessageList.Elements[0].Text = (await RepoHelper.Repo.GetNewMessagesCountAsync()).ToString();

            EmailMessaging.Delivered += EmailMessaging_Delivered;

            //foreach (var container in this.windowsUIViewMain.ContentContainers)
            //{
            //    if (container is Page)
            //    {
            //        Page page = container as Page;

            //        page.AppearanceButton.Normal.ForeColor = System.Drawing.Color.FromArgb(0x02, 0x53, 0x8E);
            //        page.AppearanceButton.Hovered.ForeColor = System.Drawing.Color.FromArgb(0, 114, 198);
            //        page.AppearanceButton.Pressed.ForeColor = System.Drawing.Color.FromArgb(0x49, 0x92, 0xC8);
            //    }
            //}

            if (Authentication.CurrentCredentials.IsEdu)
            {
                await DBLogHelper.LogLoginAsync(Authentication.CurrentCredentials);
            }

            progressDialog.HideTop();
            this.flyoutPanel1.ShowPopup();
        }

        void EmailMessaging_Delivered(object sender, EmailMessaging.DeliveryMessageArgs e)
        {
            messageControl.ShowFlyoutMessageBox(e.Caption, e.Message, FlyoutCommand.OK);
        }

        private void TriggerControlsWithPrivilegies(Credentials user)
        {
            if (user.IsEdu || user.IsMunicipality || user.IsAdmin)
            {
                tileContainerMain.Items.Add(tileSpreadsheet);
            }
            if (user.IsAdmin)
            {
                tileContainerMain.Items.Add(tileDictionaries);
                tileContainerMain.Items.Add(tileDictQuestionary);
                tileContainerMain.Items.Add(tileMessageList);
            }
            
            if (user.IsAdmin || user.IsMunicipality || user.IsMinistry)
            {
                tileContainerMain.Items.Add(tileMunicipalityForms);
                tileContainerMain.Items.Add(tileArchiveMunicipalityForms);
                tileContainerMain.Items.Add(tileDocumentQueries);
                if (!user.IsMinistry)
                    tileContainerMain.Items.Add(tileCreateQuery);

                tileContainerMain.Items.Add(tileFormStatistics);
                if (user.IsMunicipality) 
                    tabbedGroupStatistics.Items.Remove(documentSignInOutLog);
            }
            if (user.IsEdu || user.IsMunicipality)
            {
                tileContainerMain.Items.Add(tileMessage);
            }
            if (user.IsEdu)
            {
                tileContainerMain.Items.Add(tileEduPasport);
                tileForms.Tag = string.Format("Forms{0}", (int)AllformType.Type.Types.Federal);
                tileAdditionalForms.Tag = string.Format("Forms{0}", (int)AllformType.Type.Types.Other);
            }

            this.loggedUserControl.Text = user.Name;
            this.loggedUserControl.Cursor = Cursors.Hand;
            if (user.IsEdu)
            {
                this.loggedUserControl.Click += (s, e) =>
                {
                    this.windowsUIViewMain.ActivateContainer(pageEduPassport);
                };
            }
            GuiUtility.NotifyAboutForms(user);
            this.loggedUserControl.Text = Authentication.CurrentCredentials.Name;
            //this.buttonShowLogs.Visible = user.IsAdmin || user.IsEdu || user.IsMunicipality;
            //RebuildNavBar(tileContainerMain);
        }

        async private void windowsUIView1_QueryControl(object sender, QueryControlEventArgs e)
        {
            //XtraUserControl c = (XtraUserControl) Activator.CreateInstance("EduFormManager", "EduFormManager.Forms." + e.Document.ControlName).Unwrap();
            try
            {
                switch (e.Document.ControlName)
                {
                    case "Questionary":
                        {
                            XtraDictionaryQuestionaryControl questionaryControl = new XtraDictionaryQuestionaryControl(this.windowsUIViewMain);
                            int? questionaryId = TagHelper.GetQuestionaryId(e.Document.Tag.ToString());
                            if (questionaryId.HasValue)
                                questionaryControl.CurrentQuestionary = RepoHelper.Repo.GetById<Questionary>(questionaryId.Value);
                            e.Control = questionaryControl;
                            break;
                        }
                    case "Queries":
                        {
                            XtraQueryControl queryControl = new XtraQueryControl(this.windowsUIViewMain)
                            {
                                FormDataSource = RepoHelper.Repo.GetFormsHaveQueries(),
                                YearDataSource = RepoHelper.Repo.GetAvailableYears(),
                                QueryPartHeadDataSource = RepoHelper.Repo.GetAll<QueryPartHead>()
                            };
                            e.Control = queryControl;
                            break;
                        }
                    case "DictCreateQuery":
                        {
                            XtraCreateQueryControl createQueryControl = new XtraCreateQueryControl(this.windowsUIViewMain)
                                {
                                    QueryPartAutocomleteSource = RepoHelper.Repo.GetAll<QueryPartAutocomplete>(),
                                    QueryPartHeadSource = RepoHelper.Repo.GetAll<QueryPartHead>()
                                };
                            if (Authentication.CurrentCredentials.IsAdmin)
                                createQueryControl.DataSourceTemplatedFormData = RepoHelper.Repo.GetAll<TemplatedFormData>();
                            else if (Authentication.CurrentCredentials.IsMunicipality)
                            {
                                var formIdList = RepoHelper.Repo.GetAll<MunicipalityOwnesFormsView>()
                                    .Where(t => t.Municipality.Id == Authentication.CurrentCredentials.ReferenceID).Select(t => t.Allform.Id)
                                    .ToList();

                                createQueryControl.DataSourceTemplatedFormData = RepoHelper.Repo.GetAll<TemplatedFormData>()
                                    .Where(t => formIdList.Contains(t.AllForm.Id))
                                    .ToList();
                            }
                            else if (Authentication.CurrentCredentials.IsEdu)
                            {
                                var formIdList = Authentication.CurrentCredentials.EduOrg.Kind.Forms.Select(t => t.Id)
                                    .ToList();

                                createQueryControl.DataSourceTemplatedFormData = RepoHelper.Repo.GetAll<TemplatedFormData>()
                                    .Where(t => formIdList.Contains(t.AllForm.Id))
                                    .ToList();
                            }
                            e.Control = createQueryControl;
                            break;
                        }
                    case "DictEdu":
                        {
                            XtraDictionaryEduControl dictionaryEduControl =
                                new XtraDictionaryEduControl(this.windowsUIViewMain)
                                {
                                    DataSourceEdu = RepoHelper.Repo.GetAll<EduOrg>().OrderBy(m => m.Name).ToList(),
                                    DataSourceMunicipality = RepoHelper.Repo.GetAll<Municipality>().OrderBy(m => m.Name).ToList(),
                                    DataSourceEduKind = RepoHelper.Repo.GetAll<EduOrgKind>().OrderBy(m => m.KindName).ToList()
                                };

                            e.Control = dictionaryEduControl;
                            break;
                        }
                    case "DictMunicipality":
                        {
                            XtraDictionaryMunitControl dictionaryMunitControl = new XtraDictionaryMunitControl(this.windowsUIViewMain)
                                {
                                    DataSourceMunicipality = RepoHelper.Repo.GetAll<Municipality>().OrderBy(m => m.Name).ToList()
                                };
                            e.Control = dictionaryMunitControl;
                            break;
                        }
                    case "DictCheck":
                        {
                            XtraDictionaryCheckControl dictionaryCheckControl = new XtraDictionaryCheckControl(this.windowsUIViewMain);
                            dictionaryCheckControl.DataSourceAllform = RepoHelper.Repo.GetAll<Allform>();
                            e.Control = dictionaryCheckControl;
                            break;
                        }
                    case "DictTemplate":
                        {
                            XtraDictionaryTemplateControl dictionaryTemplateControl = new XtraDictionaryTemplateControl(this.windowsUIViewMain);
                            dictionaryTemplateControl.DataSourceTemplatedFormData = RepoHelper.Repo.GetAll<TemplatedFormData>();
                            e.Control = dictionaryTemplateControl;
                            break;
                        }
                    case "DictForms":
                        {
                            XtraDictionaryFormsControl dictionaryFormControl = new XtraDictionaryFormsControl(this.windowsUIViewMain)
                                {
                                    DataSourceAllform = RepoHelper.Repo.GetAll<Allform>().OrderBy(m => m.Name).ToList(),
                                    DataSourceEduKind = RepoHelper.Repo.GetAll<EduOrgKind>().OrderBy(m => m.KindName).ToList(),
                                    DataSourceAllformType = RepoHelper.Repo.GetAll<AllformType>()
                                };

                            e.Control = dictionaryFormControl;
                            break;
                        }
                    case "DictMunicipalityFormula":
                        {
                            XtraDictionaryMunicipalityFormulaControl dictionaryMunicipalityFormulaControl = new XtraDictionaryMunicipalityFormulaControl(this.windowsUIViewMain);
                            e.Control = dictionaryMunicipalityFormulaControl;
                            dictionaryMunicipalityFormulaControl.RegularFormDataSource = RepoHelper.Repo.GetFormListByType(AllformType.Type.Types.Federal)
                                .Where(t => t.Template != null)
                                .OrderBy(t => t.Name).ToList();
                            dictionaryMunicipalityFormulaControl.SummaryFormDataSource = RepoHelper.Repo.GetFormListByType(AllformType.Type.Types.Municipality)
                                .Where(t => t.Template != null)
                                .OrderBy(t => t.Name).ToList();
                            break;
                        }
                    case "ArchiveFormData3":
                    case "FormData3": //форма муниципалитета
                        {
                            int? dataId = TagHelper.GetFormDataId(e.Document.Tag.ToString());
                            if (dataId.HasValue)
                            {
                                MunicipalityFormData fd = RepoHelper.Repo.GetById<MunicipalityFormData>(dataId.Value);
                                sheetControl = new XtraSpreadsheet(this.windowsUIViewMain)
                                {
                                    DataSourceAllform = RepoHelper.Repo.GetFormListByType(AllformType.Type.Types.Municipality),
                                    FormData = fd,
                                    FormStatus = fd.Status,
                                    Source = XtraSpreadsheet.FormSource.File,
                                    Mode = XtraSpreadsheet.ControlMode.Edit,
                                    ActiveForm = fd.Form
                                };
                                sheetControl.LoadDocument();

                                e.Control = sheetControl;
                            }
                            else
                            {
                                e.Control = new Control();
                            }
                            break;
                        }
                    case "ArchiveFormData1":
                    case "ArchiveFormData2":
                    case "FormData2":
                    case "FormData1": //форма организации
                        {
                            int? dataId = TagHelper.GetFormDataId(e.Document.Tag.ToString());
                            if (dataId.HasValue)
                            {
                                EduFormData fd = RepoHelper.Repo.GetById<EduFormData>(dataId.Value);
                                sheetControl = new XtraSpreadsheet(this.windowsUIViewMain)
                                {
                                    DataSourceAllform = Authentication.CurrentCredentials.IsEdu ? Authentication.CurrentCredentials.EduOrg.Kind.Forms.OrderBy(t => t.Name).ToList() :
                                                                           RepoHelper.Repo.GetAll<Allform>().OrderBy(t => t.Name).ToList(),
                                    FormData = fd,
                                    FormStatus = fd.Status,
                                    Source = XtraSpreadsheet.FormSource.File,
                                    Mode = XtraSpreadsheet.ControlMode.Edit,
                                    ActiveForm = fd.Form
                                };
                                sheetControl.LoadDocument();

                                e.Control = sheetControl;
                            }
                            else
                            {
                                e.Control = new Control();
                            }
                            break;
                        }
                    case "XtraProgress":
                        e.Control = new XtraProgress();
                        break;
                    case "Authentication":
                        e.Control = authForm;
                        break;
                    case "Pasport":
                        {
                            passportControl = new XtraDictionaryEduPassportControl(this.windowsUIViewMain)
                            {
                                DataSourceMunicipality = RepoHelper.Repo.GetAll<Municipality>().OrderBy(m => m.Name).ToList(),
                                DataSourceActivityType = RepoHelper.Repo.GetAll<ActivityType>().OrderBy(m => m.TypeName).ToList(),
                                DataSourceEduStatus = RepoHelper.Repo.GetAll<EduOrgStatus>().OrderBy(m => m.StatusName).ToList(),
                                DataSourceEduType = RepoHelper.Repo.GetAll<EduOrgType>().OrderBy(m => m.TypeName).ToList(),
                                DataSourceEduKind = RepoHelper.Repo.GetAll<EduOrgKind>().OrderBy(m => m.KindName).ToList(),
                                DataSourceManagementAgency = RepoHelper.Repo.GetAll<ManagementAgency>().OrderBy(m => m.AgencyName).ToList(),
                                DataSourceManagementAgencyActivity = RepoHelper.Repo.GetAll<ManagementAgencyActivity>().OrderBy(m => m.AgencyActivityName).ToList(),
                                DataSourceOwnershipType = RepoHelper.Repo.GetAll<OwnershipType>().OrderBy(m => m.TypeName).ToList(),
                                Edu = Authentication.CurrentCredentials.EduOrg
                            };
                            e.Control = passportControl;
                            break;
                        }
                    case "UploadSheetFromFile":
                        {
                            sheetControl = new XtraSpreadsheet(this.windowsUIViewMain)
                            {
                                Source = XtraSpreadsheet.FormSource.File,
                                Mode = XtraSpreadsheet.ControlMode.New
                            };
                            if (Authentication.CurrentCredentials.IsEdu)
                            {
                                sheetControl.DataSourceAllform = Authentication.CurrentCredentials.EduOrg.Kind.Forms.OrderBy(t => t.Name).ToList();
                                sheetControl.ActiveForm = Authentication.CurrentCredentials.EduOrg.Kind.Forms.FirstOrDefault();
                            }
                            else if (Authentication.CurrentCredentials.IsMunicipality)
                            {
                                IList<Allform> formList = RepoHelper.Repo.GetFormListByType(AllformType.Type.Types.Municipality).OrderBy(t => t.Name).ToList();
                                sheetControl.DataSourceAllform = formList;
                                sheetControl.ActiveForm = formList.FirstOrDefault();
                            }
                            e.Control = sheetControl;
                            break;
                        }
                    case "UploadSheetFromTemplate":
                        {
                            sheetControl = new XtraSpreadsheet(this.windowsUIViewMain)
                            {
                                Source = XtraSpreadsheet.FormSource.Template,
                                Mode = XtraSpreadsheet.ControlMode.New
                            };
                            if (Authentication.CurrentCredentials.IsEdu)
                            {
                                sheetControl.DataSourceAllform = Authentication.CurrentCredentials.EduOrg.Kind.Forms.OrderBy(t => t.Name).ToList();
                                sheetControl.ActiveForm = Authentication.CurrentCredentials.EduOrg.Kind.Forms.FirstOrDefault();
                            }
                            else if (Authentication.CurrentCredentials.IsMunicipality)
                            {
                                IList<Allform> formList = RepoHelper.Repo.GetFormListByType(AllformType.Type.Types.Municipality).OrderBy(t => t.Name).ToList();
                                sheetControl.DataSourceAllform = formList;
                                sheetControl.ActiveForm = formList.FirstOrDefault();
                            }
                            else if (Authentication.CurrentCredentials.IsAdmin)
                            {
                                IList<Allform> formList = RepoHelper.Repo.GetAll<Allform>().OrderBy(t => t.Name).ToList();
                                sheetControl.DataSourceAllform = formList;
                                sheetControl.ActiveForm = formList.FirstOrDefault();
                            }
                            e.Control = sheetControl;
                            break;
                        }
                    case "RequestQuery":
                        {
                            messageControl = new XtraMessageControl(this.windowsUIViewMain)
                            {
                                MessageType = XtraMessageControl.MessageTypeEnum.RequestForQuery,
                                DataSourceAllform = RepoHelper.Repo.GetAll<Allform>().OrderBy(t => t.Name).ToList()
                            };

                            e.Control = messageControl;
                            break;
                        }
                    case "BugReport":
                        {
                            messageControl = new XtraMessageControl(this.windowsUIViewMain);
                            messageControl.MessageType = XtraMessageControl.MessageTypeEnum.BugReport;
                            e.Control = messageControl;
                            break;
                        }
                    case "MessageList":
                        {
                            XtraMessageListControl messageListControl = new XtraMessageListControl(this.windowsUIViewMain);
                            messageListControl.DataSourceMessage = RepoHelper.Repo.GetMessages().OrderByDescending(t => t.SendDate).ToList();
                            e.Control = messageListControl;
                            break;
                        }
                    case "FormDetailedStatisticsReport":
                    {
                        BaseDocument doc = this.windowsUIViewMain.Documents.FindFirst(t => t.ControlName == "FormDetailedStatistics");
                        IList<DetailedFormStatistic> formStatData = new List<DetailedFormStatistic>();
                        if (doc != null)
                        {
                            var control = doc.Control as XtraFormDetailedStatisticControl;
                            formStatData = control.FormStatisticDataSource;
                        }
                        XtraDetailedFormStatisticReport formStatisticReport = new XtraDetailedFormStatisticReport();
                        XtraReportViewControl formStatisticReportControl =
                            new XtraReportViewControl(this.windowsUIViewMain);
                        e.Control = formStatisticReportControl;
                        
                        formStatisticReport.FormStatisticDataSource = formStatData;
                        formStatisticReportControl.Report = formStatisticReport;
                        formStatisticReport.CreateDocument(true);
                        break;
                    }
                    case "FormDetailedStatistics":
                        {
                            XtraFormDetailedStatisticControl control = new XtraFormDetailedStatisticControl(this.windowsUIViewMain);
                            e.Control = control;
                            control.FormStatisticDataSource = Authentication.CurrentCredentials.IsMunicipality ?
                                await RepoHelper.Repo.GetDetailedFormStatisticsForYearAsync(DateTime.Now.Year, Authentication.CurrentCredentials.Municipality) :
                                await RepoHelper.Repo.GetDetailedFormStatisticsForYearAsync(DateTime.Now.Year);
                            control.YearsDataSource = await RepoHelper.Repo.GetAvailableYearsAsync();
                            break;
                        }
                    case "FormStatistics":
                        {
                            XtraFormStatisticReport formStatisticReport = new XtraFormStatisticReport();
                            XtraReportViewControl formStatisticReportControl = new XtraReportViewControl(this.windowsUIViewMain);

                            e.Control = formStatisticReportControl;

                            formStatisticReport.FormStatisticDataSource = Authentication.CurrentCredentials.IsMunicipality ?
                                await RepoHelper.Repo.GetFormStatisticAsync(Authentication.CurrentCredentials.Municipality) :
                                await RepoHelper.Repo.GetFormStatisticAsync();
                            formStatisticReportControl.Report = formStatisticReport;
                            formStatisticReport.CreateDocument(true);
                            break;
                        }
                    case "FormStatisticsSummary":
                        {
                            XtraFormStatisticSummaryReport formStatisticReport = new XtraFormStatisticSummaryReport();
                            XtraReportViewControl formStatisticReportControl = new XtraReportViewControl(this.windowsUIViewMain);

                            e.Control = formStatisticReportControl;

                            IList<FormStatisticSummary> formStatData = Authentication.CurrentCredentials.IsMunicipality ? 
                                await RepoHelper.Repo.GetFormStatisticSummaryAsync(Authentication.CurrentCredentials.Municipality) :
                                await RepoHelper.Repo.GetFormStatisticSummaryAsync();
                            formStatisticReport.FormStatisticSummaryDataSource = formStatData;
                            formStatisticReportControl.Report = formStatisticReport;
                            formStatisticReport.CreateDocument(true);
                            break;
                        }
                    case "SignInOutLog":
                        {
                            XtraSignInOutReport signInOutReport = new XtraSignInOutReport();
                            XtraReportViewControl signInOutReportControl = new XtraReportViewControl(this.windowsUIViewMain);

                            e.Control = signInOutReportControl;

                            IList<Log> logs = RepoHelper.Repo.GetSignInOutLogs();
                            signInOutReport.SignInOutLogDataSource = logs;
                            signInOutReportControl.Report = signInOutReport;
                            signInOutReport.CreateDocument(true);
                            break;
                        }
                    case "ExportReport":
                        {
                            XtraExportReportControl exportControl = new XtraExportReportControl();
                            e.Control = exportControl;
                            break;
                        }
                    default:
                        e.Control = new Control();
                        break;
                }
            }
            catch (Exception ex)
            {
                GuiUtility.ShowFlyoutMessage(windowsUIViewMain, flyoutMessage, "Ошибка", ex.Message + "\n" + ex.InnerException ?? ex.InnerException.Message, FlyoutCommand.OK);
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
                e.Control = new Control();
            }
        }

        private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            FlyoutAction closeAppAction = new FlyoutAction()
            {
                Caption = "Выход",
                Description = "Выйти из приложения?"
            };
            flyoutQuit.Action = closeAppAction;

            DialogResult res = windowsUIViewMain.ShowFlyoutDialog(flyoutQuit);
            if (res == DialogResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                if (Authentication.CurrentCredentials != null && Authentication.CurrentCredentials.IsEdu)
                    DBLogHelper.LogLogout(Authentication.CurrentCredentials);
            }
        }

        private void windowsUIViewMain_FlyoutHiding(object sender, FlyoutCancelEventArgs e)
        {
            WindowsUIView view = sender as WindowsUIView;
            Flyout fly = view.ActiveFlyoutContainer as Flyout;
            if (fly == null)
                return;
            FlyoutResultCancelEventArgs ee = e as FlyoutResultCancelEventArgs;
            if (fly.Document == documentLogin)
            {
                switch (ee.Result)
                {
                    case DialogResult.OK:
                        AuthenticationForm.AuthenticationRequestArgs args = authForm.Args;
                        try
                        {
                            Authentication.CurrentCredentials = auth.GetAuthenticated(args.UserName, args.Password);
                            this.tileEduPasport.Tag = Authentication.CurrentCredentials.IsEdu ? Authentication.CurrentCredentials.EduOrg.Id : 0;

                            TriggerControlsWithPrivilegies(Authentication.CurrentCredentials);
                            SomeInitialization();

                            Settings.Default.LastLogin = args.UserName;
                            Settings.Default.Save();
                        }
                        catch (InvalidCredentialException)
                        {
                            authForm.labelError.Visible = true;
                            e.Cancel = true;
                        }
                        catch (Exception ex)
                        {
                            GuiUtility.ShowFlyoutMessage(windowsUIViewMain, flyoutMessage, "Ошибка", ex.Message, FlyoutCommand.OK);
                            logger.Error(ex.Message);
                            logger.Error(ex.StackTrace);
                            if (ex.InnerException != null)
                            {
                                logger.Error("inner {0}", ex.InnerException.Message);
                                logger.Error("inner {0}", ex.InnerException.StackTrace);
                            }
                            e.Cancel = true;
                        }
                        break;
                    case DialogResult.Cancel:
                        e.Cancel = false;
                        this.Close();
                        break;
                }
            }
            else if (fly.Document == documentExportReport)
            {
                switch (ee.Result)
                {
                    case DialogResult.OK:
                        try
                        {   
                            IContentContainer f = view.ActiveContentContainer;
                            XtraExportReportControl exportControl = (XtraExportReportControl) fly.Document.Control;
                            XtraReportViewControl reportViewControl = null;
                            TabbedGroup pageGroupContainer = f as TabbedGroup;
                            if (pageGroupContainer != null)
                            {
                                reportViewControl = (XtraReportViewControl) pageGroupContainer.SelectedDocument.Control;
                            }
                            else
                            {
                                GuiUtility.ShowFlyoutMessage(windowsUIViewMain, flyoutMessage, "Ошибка", "Неизвестная ошибка", FlyoutCommand.OK);
                                return;
                            }
                            switch (exportControl.Format)
                            {
                                case XtraExportReportControl.ExportFormat.Xslx:
                                    reportViewControl.ExportToXlsx(exportControl.FileName);
                                    break;
                                case XtraExportReportControl.ExportFormat.Pdf:
                                    reportViewControl.ExportToPdf(exportControl.FileName);
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {
                            GuiUtility.ShowFlyoutMessage(windowsUIViewMain, flyoutMessage, "Ошибка", ex.Message, FlyoutCommand.OK);
                            logger.Error(ex.Message);
                            logger.Error(ex.StackTrace);
                            if (ex.InnerException != null)
                            {
                                logger.Error("inner {0}", ex.InnerException.Message);
                                logger.Error("inner {0}", ex.InnerException.StackTrace);
                            }
                        }
                        break;
                    case DialogResult.Cancel:
                        e.Cancel = false;
                        break;
                }
            }
        }
        private void mainForm_Shown(object sender, EventArgs e)
        {
            FlyoutAction loginAction = new FlyoutAction()
            {
                Caption = "Вход",
                Commands = { FlyoutCommand.OK, FlyoutCommand.Cancel }
            };
            flyoutLogin.Action = loginAction;
            windowsUIViewMain.ActivateContainer(flyoutLogin);
        }

        private void mainForm_SizeChanged(object sender, EventArgs e)
        {

        }

        async private void windowsUIViewMain_ContentContainerActivated(object sender, ContentContainerEventArgs e)
        {
            if (Authentication.CurrentCredentials == null) return;
            RebuildNavBar(e.ContentContainer);
            if (e.ContentContainer.Subtitle == tileContainerMain.Subtitle && Authentication.CurrentCredentials.IsAdmin)
            {
                int count = await RepoHelper.Repo.GetNewMessagesCountAsync();
                tileMessageList.Elements[0].Text = count.ToString();
            }
            if (e.ContentContainer == tileContainerMain)
                this.windowsUIViewMain.ActivateContainer(tileContainerMain);
        }

        private void RebuildNavBar(IContentContainer container)
        {
            if (container == null) return;
            this.navigationBar1.ClearItems();
            while (container != null)
            {
                this.navigationBar1.PushItem(container);
                container = container.Parent;
            }
        }

        private void windowsUIViewMain_BackButtonClick(object sender, BackButtonClickEventArgs e)
        {
            if (windowsUIViewMain.ActiveDocument == null)
            {
                return;
            }
            if (windowsUIViewMain.ActiveDocument == documentEduPasport)
            {
                DialogResult dialogResult = passportControl.WarnAboutSavingChanges();
                switch (dialogResult)
                {
                    case DialogResult.Yes:
                        passportControl.Save();
                        windowsUIViewMain.Controller.Back();
                        break;
                    case DialogResult.No:
                        windowsUIViewMain.Controller.Back();
                        break;
                }
                e.Handled = true;
            }
            else if (windowsUIViewMain.ActiveDocument == documentUploadSheetFromFile || windowsUIViewMain.ActiveDocument.ControlName == "FormData")
            {
                DialogResult dialogResult = sheetControl.WarnAboutSavingChanges();
                switch (dialogResult)
                {
                    case DialogResult.Yes:
                        sheetControl.OnWarnWasAnsweredYes();
                        windowsUIViewMain.Controller.Back();
                        break;
                    case DialogResult.No:
                        windowsUIViewMain.Controller.Back();
                        break;
                }
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        private void windowsUIViewMain_ControlReleasing(object sender, ControlReleasingEventArgs e)
        {
            if (e.Document != documentFormDetailedStatistics)
                e.KeepControl = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //if (this.windowsUIViewMain.ActiveDocument != null && this.windowsUIViewMain.ActiveContentContainer.Parent != null)
            //{
            //    this.windowsUIViewMain.ActivateContainer(this.windowsUIViewMain.ActiveContentContainer.Parent);
            //}
            //RepositoryFactory.Instance.Repository.Session.Clear();
        }

        private void windowsUIViewMain_NavigatedFrom(object sender, NavigationEventArgs e)
        {
            if (e.Document != null && !string.IsNullOrEmpty(e.Document.ControlName))
            {
                if (e.Document.ControlName.Contains("Dict"))
                {
                    //this.buttonRefresh.PerformClick();
                    //repo.UpdateObjectState<EduOrg>(ref loggedUser);
                }
            }
            if (e.Source == tileContainerMain)
            {
                this.docContainer.MaximumSize = new Size(0, 0);
                this.docContainer.Height = this.ClientRectangle.Height - tableLayoutPanel1.Height -
                                           navigationBar1.Height - splitContainerControl2.SplitterBounds.Height;
                //typeof(Control).GetMethod("OnResize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this.docContainer, new object[] { EventArgs.Empty });
            }
        }

        private void windowsUIViewMain_NavigatedTo(object sender, NavigationEventArgs e)
        {
            if (e.Target == tileContainerMain)
            {
                this.docContainer.MaximumSize = new Size(0,573);
                var height = this.ClientRectangle.Height - tableLayoutPanel1.Height -
                                           navigationBar1.Height - splitContainerControl2.SplitterBounds.Height;
                this.docContainer.Height = Height > this.docContainer.MaximumSize.Height ? 573 : height;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            this.flyoutPanel1.ShowPopup();
        }

        private void flyoutPanel1_ButtonClick(object sender, FlyoutPanelButtonClickEventArgs e)
        {
            if (e.Button.Caption == "Close")
            {
                this.flyoutPanel1.HidePopup();
            }
        }

        private void buttonShowLogs_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Path.Combine(Application.StartupPath, "logs");
                if (Directory.Exists(path))
                {
                    Process.Start(path);
                }
                else
                {
                    MessageBox.Show("Логов нет.");
                }

            }
            catch (Win32Exception)
            {
                MessageBox.Show("Логов нет.");
            }
        }

        private void documentManagerMain_ViewChanged(object sender, DevExpress.XtraBars.Docking2010.ViewEventArgs args)
        {
            Debug.WriteLine(args.View.ToString());
        }

        
    }
}
